package com.foreverwin.mes.lims.controller;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.model.InspecArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.lims.service.SourceDataRecordService;
import com.foreverwin.mes.lims.model.SourceDataRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 *
 * @author Levy
 * @since 2020-03-02
 */
@Controller
@RequestMapping("/sourceDataRecords")
public class SourceDataRecordController {
    private final Logger logger = LoggerFactory.getLogger(SourceDataRecordController.class);

    @Autowired
    public SourceDataRecordService sourceDataRecordService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getSourceDataRecordById(@PathVariable String id) {
        SourceDataRecord result;
        try {
            result = sourceDataRecordService.selectById(id);
        } catch (Exception e) {
            logger.error("getSourceDataRecordById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getSourceDataRecordList(SourceDataRecord sourceDataRecord){
        List<SourceDataRecord> result;
        try {
            EntityWrapper<SourceDataRecord> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(sourceDataRecord);
            result = sourceDataRecordService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getSourceDataRecordList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getSourceDataRecordPageList")
    public AjaxResult getSourceDataRecordPageList(FrontPage<SourceDataRecord> frontPage, SourceDataRecord sourceDataRecord){
        Page result;
        try {
            String site = CommonMethods.getSite();
            sourceDataRecord.setSite(site);
            EntityWrapper<SourceDataRecord> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(sourceDataRecord);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("site", frontPage.getGlobalQuery())
                    .or().like("taskId", frontPage.getGlobalQuery())
                    .or().like("param", frontPage.getGlobalQuery())
                    .or().like("inspectStandard", frontPage.getGlobalQuery())
                    .or().like("standardUnit", frontPage.getGlobalQuery())
                    .or().like("inspectParam", frontPage.getGlobalQuery())
                    .or().like("seq", frontPage.getGlobalQuery())
                    .or().like("createdUser", frontPage.getGlobalQuery())
                    .or().like("updatedUser", frontPage.getGlobalQuery())
        ;
            }
            result = sourceDataRecordService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getSourceDataRecordPageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param jsonObject  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult sourceDataRecordSave(@RequestBody JSONObject jsonObject) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        try {

            //参数
            String taskNo = (String)jsonObject.get("taskNo");
            Integer total = (Integer)jsonObject.get("total");

            List<Map> todolist = (List<Map>) jsonObject.get("todolist");

            if ( todolist.isEmpty() ){
                throw BusinessException.build("缺少源数据明细!");
            }
            sourceDataRecordService.doSave( site , taskNo ,total ,user , todolist );
        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }

        return AjaxResult.success("源数据维护成功！");
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult sourceDataRecordDelete(@PathVariable("id") String id){
        int count;
        try {
            count = sourceDataRecordService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("sourceDataRecordDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = sourceDataRecordService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("sourceDataRecordBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }
}